<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/5/29
 * Time: 下午9:04
 */

namespace app\webapi\controller;


use app\common\controller\Api;
use app\behavior;
use think\Cookie;
use think\Db;
use think\Request;
use app\common;
use think\Loader;

class User extends Api
{

    /**
     * 用户微信登陆，如果已存在则直接返回登陆状态，如果不存在返回错误信息
     * @return array|\think\response\Json
     */
    public function login()
    {
        $data = input('post.');
        $result = $this->validate(input('post.'),'User.add');
        if($result !== true){
            return api_error('1000',$result);
        }

        // 校验登录短信
        $config = common\Config::$alidayu;
        $template = $config['login_template_code'];
        $code = Db::name('message')->where(['number'=>input('post.code'),'mobile'=>input('post.mobile'),'template'=>'SMS_84695285'])->order('id desc')->find();

        //验证码1小时内有效
        if(!empty($code)){
            $time = strtotime($code['create_time'])+3600;
            if($time < time()){
                return api_error('1004','对不起，您输入的验证码已过期');
            }else{
                $user = model('User');
                $userInfo = $user->where(['mobile'=>$data['mobile'],'status'=>1])->find();
                if(!empty($userInfo)){
                    if($userInfo['status'] != 1){
                        return api_error('1006','对不起，您已被禁止登陆！');
                    }
                    // 更新用户登陆信息
                    $updateData = [
                        'last_login_ip' => Request::instance()->ip(),
                        'last_login_time' => date('Y-m-d H:i:s'),
                        'login_times' => $userInfo['login_times']+1
                    ];
                    $updateUser = $user->isUpdate(true)->save($updateData,['mobile' => $data['mobile'],'status' => 1]);
                    $userInfo['token'] = $this->getAuthToken($userInfo['id']);
                    return api_return('操作成功！',$userInfo);
                }else{
                    // 插入用户登陆信息
                    $insertData = [
                        'mobile' => input('post.mobile'),
                        'last_login_ip' => Request::instance()->ip(),
                        'last_login_time' => date('Y-m-d H:i:s'),
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s'),
                        'login_times' => 1,
                        'status' => 1
                    ];
                    $result = $user->insertGetId($insertData);
                    if($result){
                        $insertData['token'] = $this->getAuthToken($result);
                        return api_return('操作成功！',$insertData);
                    }else{
                        return api_error('1007','用户注册失败，请重试！');
                    }
                }
            }
        }else{
            return api_error('1005','对不起，您输入的验证码有误');
        }

    }

    /**
     * 用户发送短信验证码 type 1-注册短信，2-校验短信，3-绑定校验短信
     * 校验短信需要验证token及用户uid
     * @return \think\response\Json
     */
    public function sendRegisterCode(){
        $mobile = input('mobile');

        // 参数校验
        $validate = $this->validate(['mobile'=>$mobile],['mobile'=> 'number|length:11']);
        if($validate !== true){
            return api_error('1000',$validate);
        }

        // 单个用户一天最多发5条信息
        $record = Db::name('message')->whereTime('create_time','today')->where('mobile',$mobile)->order('id desc')->select();
        if(count($record) >5){
            return api_error('1001','对不起，您发送短信已超过规定次数！');
        }
        // 一分钟内无法再次发送
        if(!empty($record)){
            $time = strtotime($record[0]['create_time'])+60;
            if($time >time()){
                return api_error('1002','短信验证码已发送，请稍后再试！');
            }
        }
        Loader::import('dysms.api_demo.SmsDemo',EXTEND_PATH);//对应extend目录，路径，如果你对SmsDemo类添加了命名空间可在上面 use 后在此处直接实例化
        $code = rand(1000,9999);

        //得到信息文件并执行.实例化阿里短信类
        $msg = new \SmsDemo('LTAI2rxAvtIgMbV6','azTBhC9T4Ni57iHDZyoecp9QboxcYj');//注意类名前面的  \ 此处写的就是Access key id 和Access key secret
        $send = $msg::sendSms($mobile,$code);
        $data = [
            'mobile' =>$mobile,
            'number' => $code,
            'template' => 'SMS_84695285',
            'create_time' => date('Y-m-d H:i:s')
        ];
        $result = Db::name('message')->insert($data);
        return api_return('发送短信成功！',array());

//        $alidayu = new common\SendMessage();
//        $code = rand(1000,9999);
//        $config = common\Config::$alidayu;
//        $template = $config['login_template_code'];
//
//        $send = $alidayu->send($mobile,$code,$template);
//        if($send){
//            $data = [
//                'mobile' =>$mobile,
//                'number' => $code,
//                'template' => $template,
//                'create_time' => date('Y-m-d H:i:s')
//            ];
//            $result = Db::name('message')->insert($data);
//            return api_return('发送短信成功！',array());
//        }else{
//            return api_error('1003','对不起，短信发送失败！');
//        }
    }

    public function authReg(){
//        $str = 'a:2:{s:4:"data";a:6:{s:11:"screen_name";s:12:"木名解说";s:7:"open_id";i:935770320008;s:12:"access_token";s:36:"73a486cdee287e206b972cf6188a372e0008";s:10:"expires_in";i:1516688299;s:8:"uid_type";i:12;s:3:"uid";i:50774708546;}s:3:"ret";i:0;}';
//        $str = unserialize($str);
//        var_dump($str);die;
        $error_code = Request::instance()->has('error_code','get');

        if($error_code){
            exit();
        }else{
            $client_key = 'a2a35922553e5378';
            $client_secret = 'ed6d4d102ce7742808636575988c79d8';

            $data['platform'] = 1;
            $data['platform_name'] = '头条号开放平台';
            $data['account'] = '';
            $data['password'] = '';
            $data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s',time());
            $data['uid'] = input('state');
            $code = input('code');
            $timestamp = time();

//            $timestamp = 123;
//            $code = 456;
//            $client_secret = 789;
            $secure_strings = array($timestamp, $code, $client_secret);

            sort($secure_strings);
            $signature = md5(''.join($secure_strings));
            $url = 'https://open.snssdk.com/auth/token/?code='.$code.'&client_key='.$client_key.'&client_secret='.$client_secret.'&grant_type=authorize_code';
//            $url = 'https://open.snssdk.com/auth/token/?code='.$code.'&client_key='.$client_key.'&timestamp='.$timestamp.'&signature='.$signature.'&grant_type=authorize_code';
            $result = doCurl($url);
            if($result['ret'] == 0){
                $data['status'] = 1;
            }else{
                $data['status'] = 2;
            }
            $data['result'] = serialize($result);
            Db::name('account')->insertGetId($data);
            echo "<script>window.close();</script>";
            exit();
        }
    }

    // 添加账户信息
    public function updateInfo(){
        $user['uid'] = input('post.uid');
        $user['token'] = input('post.token');

        $rule = [
            'uid' => 'require|number',
            'token' => 'require',
        ];
        $data = input('post.');
        $validate = $this->validate($user,$rule);
        $v2 = $this->validate($data,'User.edit');

        if($validate !== true){
            return api_error('1000',$validate);
        }
        if($v2 !== true){
            return api_error('1000',$v2);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        unset($data['uid'],$data['token']);
        $result = Db::name('user')->where("id = ".$user['uid'])->update($data);
        if($result == false){
            return api_error('1004','修改信息失败！');
        }else{
            return api_return('操作成功！','');
        }
    }

    // 用户提现
    public function cash(){
        $user['uid'] = input('post.uid');
        $user['token'] = input('post.token');
        $user['money'] = input('post.money');

        $rule = [
            'uid' => 'require|number',
            'token' => 'require',
            'money' => 'require|number'
        ];
        $data = input('post.');
        $validate = $this->validate($user,$rule);

        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($user['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        //  总收益
        $count = Db::name("video")->field("sum(earnings) as money,count(id) as num,sum(play) as play")->where("ad = 1 and uid = ".$data['uid'])->select();
        $total = $count[0]['money']?$count[0]['money']:"0.00";

        // 已提现总额度
        $model = Db::name('money');
        $cashes = $model->field("sum(money) as money")->where("status = 1 and uid = ".$data['uid'])->find();
        $cash = $cashes['money']?$cashes['money']:"0.00";
        // 计算可提现金额
        $money = $total-$cash;
        // 判断是否超额
        if($money < input('post.money')){
            return api_error('4','对不起，您的余额不足，无法提现!');
        }

        // 税率
        $tax = 0.01;
        $data['tax'] = $tax*$data['money'];
        $data['true_money'] = $data['money'] - $data['tax'];


        unset($data['token']);
        $result = $model->insert($data);
        if($result){
            return api_return('申请提现成功！请耐心等待结果！','');
        }else{
            return api_error('1004','申请提现信息失败！');
        }
    }

    // 用户提现列表
    public function cashList(){
        $user['uid'] = input('post.uid');
        $user['token'] = input('post.token');
        $page = input('post.page')?input('post.page'):1;
        $pageSize = 5;
        $rule = [
            'uid' => 'require|number',
            'token' => 'require',
        ];
        $validate = $this->validate($user,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($user['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }

        //  总收益
        $count = Db::name("video")->field("sum(earnings) as money,count(id) as num,sum(play) as play")->where("ad = 1 and uid = ".$user['uid'])->select();
        $total = $count[0]['money']?$count[0]['money']:"0.00";

        // 已提现总额度
        $model = Db::name('money');
        $cashes = $model->field("sum(money) as money")->where("status = 1 and uid = ".$user['uid'])->find();
        $cash = $cashes['money']?$cashes['money']:"0.00";

        // 记录总数
        $num = $model->where("uid = ".$user['uid'])->count();
        $result['pages'] = ceil($num/$pageSize);
        // 总收益
        $result['total'] = $total;
        // 计算可提现金额
        $money = $total-$cash;
        $result['money'] = $money;
        $data = $model->where("uid = ".$user['uid'])->order("id desc")->page($page,$pageSize)->select();
        $result['data'] = $data;
        return api_return('操作成功！',$result);
    }
    public function test(){
        $number = input('number');//input助手函数   获取输入数据 支持默认值和过滤

        Loader::import('dysms.api_demo.SmsDemo',EXTEND_PATH);//对应extend目录，路径，如果你对SmsDemo类添加了命名空间可在上面 use 后在此处直接实例化

        $code = '12346';

        //得到信息文件并执行.实例化阿里短信类
        $msg = new \SmsDemo('LTAI2rxAvtIgMbV6','azTBhC9T4Ni57iHDZyoecp9QboxcYj');//注意类名前面的  \ 此处写的就是Access key id 和Access key secret
$s = $msg::sendSms($number,$code);
        //此配置在sdk包中有相关例子
        $res = $msg->sendSms(
        //短信签名名称
            "传传科技",//此处填写你在阿里云平台配置的短信签名名称（第二步有说明）
            //短信模板code
            "SMS_84695285",//此处填写你在阿里云平台配置的短信模板code（第二步有说明）
            //短信接收者的手机号码
            " $number",
            //模板信息
            Array(
                'number' => $code,//随机变化的
            )
        );
        dump($res);die;
        $response = array($res);
    }
}